<template>
	<view class="login">
		<!-- logo -->
		<view class="u-m-t-60 u-m-l-60">
			<u-image border-radius="16"
				:src="logo || 'https://aihelp.oss-cn-hangzhou.aliyuncs.com/public/base/2023/12/17/6e0adaf38bc74aa6825fe711d1dff582.jpg'"
				width="200" height="200"></u-image>
		</view>
		<!-- 账号密码登录 -->
		<view class="loginForm loginPass" v-if="loginType==1">
			<view class="loginTitle flex align-end color333 u-m">
				<view class="u-font-40 ">{{mineProgramTitle || '新助邦'}}</view>
				<view class="u-p-l-5 u-p-r-5 u-font-32">-</view>
				<view class="u-font-32">{{mineProgramSubTitle || '考研择校调剂上岸之神'}}</view>
				<text class="mathMagrin u-font-24 color666"
					@click.stop="changeLoginType(loginType==1?2:1)">{{loginType==1?'短信登录':'账号登录'}}</text>
			</view>
			<view class="inputItem flex alignCenter justConBetween">
				<image src="@/static/image/icons/tel2.png" mode="widthFix"></image>
				<input class="font14" type="number" v-model.trim="loginForm.username" maxlength="11" placeholder="请输入手机号">
				<uni-icons class="clear" type="clear" color="#ccc" size="18" @click="loginForm.username=''"
					v-if="loginForm.username"></uni-icons>
			</view>
			<view class="inputItem flex alignCenter justConBetween">
				<image src="@/static/image/icons/pass.png" mode="widthFix"></image>
				<input class="font14" type="text" v-model.trim="loginForm.password" v-if="showPass" maxlength="20"
					placeholder="请输入密码">
				<input class="font14" password v-model.trim="loginForm.password" v-if="!showPass" maxlength="20"
					placeholder="请输入密码">
				<view style="width: 60rpx;height: 60rpx;" class="flex align-center justify-evenly"
					@click="showPass = !showPass">
					<uni-icons v-if="showPass" color="#ccc" class="inputIcon" type="eye" size="18"></uni-icons>
					<uni-icons v-if="!showPass" color="#ccc" class="inputIcon" type="eye-slash" size="18"></uni-icons>
				</view>
			</view>
			<!-- #ifdef APP-PLUS || H5 -->
			<view class="inputItem flex alignCenter justConBetween">
				<image src="@/static/image/icons/ver.png" mode="widthFix"></image>
				<input class="font14" type="number" v-model.trim="loginForm.invitationCode" maxlength="19" placeholder="邀请码">
				<uni-icons class="clear" type="clear" color="#ccc" size="18" @click="loginForm.invitationCode=''"
					v-if="loginForm.invitationCode"></uni-icons>
			</view>
			<!-- #endif -->
		</view>
		<!-- 手机号验证码登录 -->
		<view class="loginForm" v-if="loginType==2">
			<view class="loginTitle flex align-end color333">
				<view class="u-font-40">{{mineProgramTitle || '新助邦'}}</view>
				<view class="u-p-l-5 u-p-r-5 u-font-32">-</view>
				<view class="u-font-32">{{mineProgramSubTitle || '考研择校调剂上岸之神'}}</view>
				<text class="mathMagrin u-font-24 color666"
					@click.stop="changeLoginType(loginType==1?2:1)">{{loginType==1?'短信登录':'账号登录'}}</text>
			</view>
			<view class="inputItem flex alignCenter justConBetween">
				<image src="@/static/image/icons/tel2.png" mode="widthFix"></image>
				<input class="font14" type="number" v-model.trim="verForm.phoneNumber" maxlength="11" placeholder="请输入手机号">
				<uni-icons class="clear" type="clear" color="#ccc" size="18" @click="verForm.phoneNumber=''"
					v-if="verForm.phoneNumber"></uni-icons>
			</view>
			<view class="inputItem flex alignCenter justConBetween">
				<image src="@/static/image/icons/ver.png" mode="widthFix"></image>
				<input class="font14" type="number" v-model.trim="verForm.verificationCode" maxlength="6" placeholder="请输入验证码">
				<uni-downtime ref="downloadRef" class="verify font14" :tel="verForm.phoneNumber"
					:msgType="'LOGIN'"></uni-downtime>
			</view>
			<!-- #ifdef APP-PLUS || H5 -->
			<view class="inputItem flex alignCenter justConBetween">
				<image src="@/static/image/icons/ver.png" mode="widthFix"></image>
				<input class="font14" type="number" v-model.trim="verForm.invitationCode" maxlength="19" placeholder="邀请码">
				<uni-icons class="clear" type="clear" color="#ccc" size="18" @click="verForm.invitationCode=''"
					v-if="verForm.invitationCode"></uni-icons>
			</view>
			<!-- #endif -->
		</view>

		<view class="noWidthBtn" @click="loginClick">登录</view>
		<!-- 公共操作 -->
		<view class="three">
			<view class="font12 agreement flex alignCenter">
				<view class="u-font-28 color333 flex align-center justify-center u-m-t-60" @click="agreeClick">
					<checkbox :checked="agree" class="agreeCheck" style="transform:scale(0.8)" />
					我已知晓并同意
					<text class="text-main-color" @click.stop="toService('service')">《用户协议》</text>
					和
					<text class="text-main-color" @click.stop="toService('personal')">《隐私协议》</text>
				</view>
			</view>
			<view class="u-font-28 totalOper"><text class="herf-color" @click="toForget">忘记密码，</text>快速<text
					class="herf-color" @click="toRegiste">注册</text></view>
		</view>
	</view>
</template>

<script>
	import {
		mobile,
		password
	} from "@/utils/verification.js"
	import {
		login,
		wxGetPhone
	} from "@/api/login.js"
	import {
		getWxCode,
		getDyCode
	} from "@/utils/common.js"
	export default {
		data() {
			return {
				loginForm: {
					appType: '',
					loginType: '',
					password: '',
					username: '',
					invitationCode: ''
				},
				verForm: {
					loginType: '',
					appType: '',
					phoneNumber: '',
					verificationCode: '',
					invitationCode: ''
				},
				loginType: 1,
				showPass: false,
				agree: false,
				wxCode: '',
				mineProgramTitle: "",
				mineProgramSubTitle: "",
				logo: ''
			}
		},
		onLoad(e) {
			this.loginType = ~~e.type;
		},
		onShow() {
			// 清空跳转标记（此字段用来防止多次跳转到登录页）
			uni.removeStorageSync('navigateLogin')
			if (uni.getStorageSync('mineProgramSys')) {
				let obj = JSON.parse(uni.getStorageSync('mineProgramSys'));
				this.mineProgramTitle = obj.mineProgramTitle;
				this.mineProgramSubTitle = obj.mineProgramSubTitle;
				this.logo = obj.logo;
			}
		},
		methods: {
			changeLoginType(type) {
				this.loginForm = {
					appType: '',
					loginType: '',
					password: '',
					username: '',
					invitationCode: ''
				}
				this.verForm = {
					loginType: '',
					appType: '',
					phoneNumber: '',
					verificationCode: '',
					invitationCode: ''
				}
				this.loginType = type
			},
			agreeClick() {
				this.agree = !this.agree
			},
			// 密码登录验证
			passLoginVer() {
				if (!(mobile.test(this.loginForm.username))) {
					uni.showToast({
						icon: 'none',
						title: '请填写标准手机号'
					})
					return
				} else if (!this.loginForm.password) {
					uni.showToast({
						icon: 'none',
						title: '请填写密码（密码必须包含大小写以及数字，长度在6-20位）'
					})
					return
				}
				// else if(!(password.test(this.loginForm.password))){
				// 	uni.showToast({
				// 		icon:'none',
				// 		title:'请填写密码（密码必须包含大小写以及数字，长度在6-20位）'
				// 	})
				// 	return
				// }
				else if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意相关政策'
					})
					return
				} else {
					this.loginApi()
				}
			},
			// 验证码登录验证
			verifyLoginVer() {
				if (!(mobile.test(this.verForm.phoneNumber))) {
					uni.showToast({
						icon: 'none',
						title: '请填写标准手机号'
					})
					return
				} else if (!this.verForm.verificationCode) {
					uni.showToast({
						icon: 'none',
						title: '请输入验证码'
					})
					return
				} else if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意相关政策'
					})
					return
				} else {
					this.loginApi()
				}
			},
			// 登录点击事件
			loginClick() {
				// #ifdef MP
				getWxCode().then((code) => {
					console.error('code===', code)
					this.wxCode = code
					if (this.loginType == 1) {
						this.passLoginVer()
					} else {
						this.verifyLoginVer()
					}
				})
				// #endif
				// #ifndef MP
				if (this.loginType == 1) {
					this.passLoginVer()
				} else {
					this.verifyLoginVer()
				}
				// #endif
			},
			// 调用登录API(只有微信获取手机号登录才有type和loginData)
			loginApi(type, loginData) {
				let loginType = type ? type : (this.loginType == 1 ? 'PASSWORD' : 'SHORT_MESSAGE')
				let param = (this.loginType == 1 ? this.loginForm : this.verForm)
				if (type == 'BIND_PHONE') {
					// 微信获取手机号
					param = {
						"loginType": loginType,
						"uuid": loginData.uuid,
						"extraData": {
							"encryptedData": loginData.encryptedData,
							"iv": loginData.iv
						},
						"appType": 1,
						"phoneNumber": loginData.phoneNumber,
						"invitationCode": this.loginForm.invitationCode || this.verForm.invitationCode || ''
					}
				} else if (type == 'PHONE_QUICK') {
					param = {
						"phoneNumber": loginData.phoneNumber,
						"phoneQuickParam": {
							"accessToken": loginData.access_token,
							"openId": loginData.openid
						},
						"invitationCode": this.loginForm.invitationCode || this.verForm.invitationCode || ''
					}
				}
				// #ifdef APP-PLUS
				param.appType = uni.getStorageSync('systemInfo').osName == 'ios' ? 3 : 2
				// #endif
				// #ifdef MP
				param.appType = 1
				// #endif
				param.loginType = loginType //this.loginType==1?'PASSWORD':'SHORT_MESSAGE'
				// #ifdef MP
				if (!type) {
					param.wechatCode = this.wxCode
				}
				// #endif
				// 若是通过扫校园推广者的分享码进入的需要绑定二者之间的关系
				if (uni.getStorageSync("shareUserId")) {
					param.u = uni.getStorageSync("shareUserId")
				}
				uni.showLoading({
					title: '登录中',
					mask: true
				})
				console.error('登录参数', param)
				login(param).then((res) => {
					console.log('res: ', res);
					uni.hideLoading()
					if (res.code == 100000) {
						if (type == 'PHONE_QUICK') {
							uni.closeAuthView()
						}
						uni.setStorageSync('token', res.data.access_token)
						uni.setStorageSync('userId', res.data.userId)
						// #ifdef APP-PLUS
						plus.runtime.agreePrivacy();
						// #endif
						if (uni.getStorageSync('prePath')) {
							// 跳转回之前进入的页面
							// #ifdef APP-PLUS || H5
							let url = uni.getStorageSync('prePath')
							// #endif
							// #ifdef MP
							let url = decodeURIComponent(uni.getStorageSync('prePath'))
							// #endif
							uni.removeStorageSync('prePath')
							if (url.indexOf('index/index') != -1 || url.indexOf('schoolMain/schoolMain') != -1 || url.indexOf(
									'major/major') != -1 || url.indexOf('mineMain/mineMain') != -1) {
								uni.switchTab({
									url: url
								})
							} else {
								uni.redirectTo({
									url: url
								})
							}
						} else {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					}
				}).catch((err) => {
					uni.hideLoading()
				})

			},
			toRegiste() {
				uni.navigateTo({
					url: '/registePages/pages/registe'
				})
			},
			toForget() {
				uni.navigateTo({
					url: '/pages/login/forgetPass/forgetPass'
				})
			},
			toService(type) {
				uni.navigateTo({
					url: '/pages/service/service?type=' + type
				})
			},
			// 游客模式
			tourModule() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			// 微信获取手机号登录登录
			decryptPhoneNumber(e) {
				if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意相关政策'
					})
					return
				}


				// #ifdef MP-TOUTIAO
				console.log('e', e)
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					uni.showLoading({
						title: '登录中',
						mask: true
					})
					getDyCode().then((code) => {
						console.error('code===', code)
						// this.wxCode = code
						// let nowObj = {
						// 	"loginType": "WECHAT_APPLET",
						// 	"appType": 1,
						// 	"authCode": this.wxCode
						// }
						return;
						if (uni.getStorageSync("shareUserId")) {
							nowObj.u = uni.getStorageSync("shareUserId")
						}
						login(nowObj).then((res) => {
							uni.hideLoading()
							if (res.code == 100000) {
								uni.setStorageSync('token', res.data.access_token)
								// 因为这个接口要进行token验证，所以需要拿微信code先调用一次登录拿到token
								wxGetPhone({
									code: e.detail.code
								}).then((res2) => {
									let wxdata = Object.assign({
										phoneNumber: JSON.parse(res2.msg).phone_info.phoneNumber,
										uuid: res.data.uuid
									}, e.detail)
									this.loginApi('BIND_PHONE', wxdata)
								})
							}
						}).catch((err) => {
							uni.hideLoading()
						})
					})
				}
				// #endif


				// #ifdef MP-WEIXIN
				// 别问为啥传这些，因为要打通之前的所有移动端的数据和逻辑，之前的是这么做的，现在这个不这么做后端会改很多，怕会出现很多bug
				// 所以微信手机号登录按照之前其他移动端的逻辑原封不动的写
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					// uni.showToast({
					// 	title:e.detail.errMsg,
					// 	duration:5000
					// })
					uni.showLoading({
						title: '登录中',
						mask: true
					})
					getWxCode().then((code) => {
						console.error('code===', code)
						this.wxCode = code
						let nowObj = {
							"loginType": "WECHAT_APPLET",
							"appType": 1,
							"authCode": this.wxCode
						}
						if (uni.getStorageSync("shareUserId")) {
							nowObj.u = uni.getStorageSync("shareUserId")
						}
						login(nowObj).then((res) => {
							uni.hideLoading()
							if (res.code == 100000) {
								uni.setStorageSync('token', res.data.access_token)
								// 因为这个接口要进行token验证，所以需要拿微信code先调用一次登录拿到token
								wxGetPhone({
									code: e.detail.code
								}).then((res2) => {
									let wxdata = Object.assign({
										phoneNumber: JSON.parse(res2.msg).phone_info.phoneNumber,
										uuid: res.data.uuid
									}, e.detail)
									this.loginApi('BIND_PHONE', wxdata)
								})
							}
						}).catch((err) => {
							uni.hideLoading()
						})
					})
				}
				// #endif
			},
			// 本机号码一键登录
			oneKeyLogin() {
				if (!this.agree) {
					uni.showToast({
						icon: 'none',
						title: '请阅读并同意相关政策'
					})
					return
				}
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				uni.preLogin({
					provider: 'univerify',
					success: (res) => {
						uni.hideLoading()
						//预登录成功
						// 显示一键登录选项
						uni.login({
							provider: 'univerify',
							univerifyStyle: { // 自定义登录框样式
								"title": '快速登录',
								"backgroundColor": "#ffffff", // 授权页面背景颜色，默认值：#ffffff
								"icon": {
									"path": "/static/logo.png" // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
								},
								"phoneNum": {
									"color": "#000000", // 手机号文字颜色 默认值：#000000
									"fontSize": "18" // 手机号字体大小 默认值：18
								},
								"slogan": {
									"color": "#8a8b90", //  slogan 字体颜色 默认值：#8a8b90
									"fontSize": "12" // slogan 字体大小 默认值：12
								},
								// 一键登录
								"authButton": {
									"normalColor": "#F7DD5E", // 授权按钮正常状态背景颜色 默认值：#3479f5
									"highlightColor": "#F7DD5E", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
									"disabledColor": "#cccccc", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
									"textColor": "#000000", // 授权按钮文字颜色 默认值：#ffffff
									"title": "本机号码一键登录" // 授权按钮文案 默认值：“本机号码一键登录”
								},
								// 其他登录方式
								"otherLoginButton": {
									"visible": "true", // 是否显示其他登录按钮，默认值：true
									"normalColor": "#f8f8f8", // 其他登录按钮正常状态背景颜色 默认值：#f8f8f8
									"highlightColor": "#dedede", // 其他登录按钮按下状态背景颜色 默认值：#dedede
									"textColor": "#000000", // 其他登录按钮文字颜色 默认值：#000000
									"title": "账号登录", // 其他登录方式按钮文字 默认值：“其他登录方式”
									"borderWidth": "1px", // 边框宽度 默认值：1px（仅ios支持）
									"borderColor": "#c5c5c5" //边框颜色 默认值： #c5c5c5（仅ios支持）
								},
								"privacyTerms": {
									"defaultCheckBoxState": "true", // 条款勾选框初始状态 默认值： true
									"textColor": "#8a8b90", // 文字颜色 默认值：#8a8b90
									"termsColor": "#F7DD5E", //  协议文字颜色 默认值： #1d4788
									"prefix": "我已阅读并同意", // 条款前的文案 默认值：“我已阅读并同意”
									"suffix": "并使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”
									"fontSize": "12", // 字体大小 默认值：12,
									"privacyItems": []
								}
							},
							success: (res2) => { // 登录成功
								console.log(res2);
								// 客户端(调用云函数)  调用云函数来实现整个业务逻辑
								// 在得到access_token后，通过callfunction调用云函数
								let _this = this
								uniCloud.callFunction({
									name: "getPhoneNumber",
									data: res2.authResult
								}).then(res3 => {
									// 获取用户的手机号
									console.log("成功", res3); // res 内容则包含手机号码
									let loginParam = Object.assign({
										phoneNumber: res3.result.data.phoneNumber
									}, res2.authResult)
									_this.loginApi('PHONE_QUICK', loginParam)
								}).catch((err) => {
									console.error('err', err)
									// 执行失败
									uni.showToast({
										title: '登录失败',
										icon: 'none'
									})
								})
							},
							// 当用户点击自定义按钮时，会触发uni.login的fail回调[点击其他登录方式，可以跳转页面]
							// 判断返回数据执行任意逻辑
							fail(res) { // 登录失败
								console.log(res.errCode)
								console.log(res.errMsg)
								if (res.code == "30002") {
									console.log('密码登录');
								} else if (res.code == "30008") {
									console.log('自定义按钮登录方式');
								} else if (res.code == "30003") {
									console.log('用户主动关闭一键登录');
								} else {
									uni.showToast({
										title: '登录失败，请联系开发人员',
										icon: 'none'
									})
								}
							}
						})
					},
					fail(res) { // 预登录失败
						uni.hideLoading()
						// 不显示一键登录选项（或置灰）
						// 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
						console.log('失败', 2222, res);
						console.log(res.errCode)
						console.log(res.errMsg)
						if (res.errMsg.indexOf('-20202') != -1) {
							uni.showToast({
								title: '请开启流量',
								icon: 'none'
							})
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/public.scss";

	.login {
		box-sizing: border-box;

		.loginDef {
			text-align: right;
			padding: 96rpx 30rpx 0; //48rpx 0 0;
			position: relative;
			height: 400rpx;
			/* #ifdef MP */
			height: 496rpx;
			/* #endif */
			overflow: hidden;
			box-sizing: border-box;

			image {
				width: 100%;
				height: 100%;
				display: block;
				margin: -96rpx auto 0;
				/* #ifdef MP */
				margin: 0 auto;
				/* #endif */
			}

			.tour {
				position: absolute;
				right: 36rpx;
				top: 96rpx; //48rpx
				/* #ifdef MP */
				top: 150rpx;
				/* #endif */
				border: 1px solid #E5E5E5;
				width: 130rpx;
				height: 50rpx;
				text-align: center;
				line-height: 50rpx;
				border-radius: 30rpx;
				z-index: 10;
			}
		}

		.loginForm {
			padding: 48rpx 66rpx 0;
			box-sizing: border-box;

			.loginTitle {
				font-size: 42rpx;
				margin-bottom: 50rpx;
				font-weight: 600;

				text {
					margin: 0 0 0 30rpx;
				}
			}

			.verify {
				color: $colorMain !important;
				z-index: 10;
			}

			input {
				border: 1px solid $bordercolor;
				height: 80rpx;
				height: 100%;
				line-height: 80rpx;
			}

			.tip {
				margin: 15rpx 0 0;
			}

			.inputItem {
				image {
					width: 48rpx;
					height: 48rpx;
					margin: 0 25rpx 0 0;
				}

				border-bottom: 1px solid $bordercolor;
				height: 80rpx;
				margin:24rpx 0 0;

				input {
					border: none;
					flex: 1;
				}
			}

			.registe {
				text-align: center;
			}
		}

		.three {
			padding: 0 58rpx 0;
			box-sizing: border-box;
			position: fixed;
			bottom: 10vh;
			left: 50%;
			transform: translate(-50%);
			width: 100%;

			.otherOper {
				margin: 24rpx 0 86rpx;
			}


			.registe {
				text-align: center;
			}

			.threeTitle {
				padding: 0 40rpx;
				box-sizing: border-box;

				.line {
					height: 1px;
					background: #ccc;
					flex: 1;
				}

				.font12 {
					margin: 0 20rpx 0;
				}
			}

			.otherWay {
				margin: 30rpx 0 0;
			}

			.totalOper {
				text-align: center;
				margin: 40rpx 0 0;
			}

			.threeLogin {
				position: relative;

				image {
					width: 86rpx;
					height: 86rpx;
				}

				.phoneBtn {
					position: absolute;
					width: 80rpx;
					height: 80rpx;
					left: 50%;
					margin-left: -40rpx;
					top: 0;
					border-radius: 50%;
					opacity: 0;
				}
			}
		}

		.noWidthBtn {
			height: 86rpx;
			line-height: 86rpx;
			border-radius: 15rpx;
			width: 634rpx;
			margin: 80rpx auto;
		}


		.agreement {
			margin: 86rpx 0 0;

			&>view {
				margin: 0 auto;
			}

			::v-deep .uni-checkbox-input {
				color: $colorMain !important;
			}

			::v-deep .uni-checkbox-input:hover {
				border-color: $colorMain !important;
				;
			}
		}
	}

	.btnBox {
		position: relative;
		padding-top: 80rpx;

		.mbbox {
			z-index: 10;
			height: 86rpx;
			width: 100%;
			background-color: transparent;
			position: absolute;
		}

		.getPhone {
			z-index: 1;
			border: none;
			border-radius: 15rpx;
			background-color: #F7DD5E;
			font-size: 28rpx;
			height: 86rpx;
			line-height: 86rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.icon {
				width: 30rpx;
				height: 30rpx;
				margin-right: 4rpx;
			}
		}

		.getPhone::after {
			border: none;
		}
	}



	#mpAgreement {
		margin: 40rpx 0 0;
	}
</style>